#!/bin/bash

# Autobuild the Image on Docker Hub with advanced options
# https://docs.docker.com/docker-hub/builds/advanced/

# if the host is not equal to the building system architecture, register qemu-*-static.

set -e

HOST_ARCH=$(uname -m)
BUILD_ARCH=$(echo "${DOCKERFILE_PATH}" | cut -d '.' -f 2)
BUILD_ARCH=$([[ "${BUILD_ARCH}" == *\/* ]] && echo "${BUILD_ARCH}" | rev | cut -d '/' -f 1 | rev || echo "${BUILD_ARCH}")
QEMU_USER_STATIC_ARCH=$([[ "${BUILD_ARCH}" == "armhf" ]] && echo "${BUILD_ARCH::-2}" || echo "${BUILD_ARCH}")

if [[ "${HOST_ARCH}" == "${QEMU_USER_STATIC_ARCH}"* || "${BUILD_ARCH}" == "Dockerfile"  ]]; then
    echo "Building ${BUILD_ARCH} image natively; qemu-user-static: Registration not required for current arch"
    exit 0
else
    # Register qemu-*-static for all supported processors except the
    # current one, but also remove all registered binfmt_misc before
    docker run --rm --privileged multiarch/qemu-user-static:register --reset
fi
